﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using FC.BCVP.NET8.IService;
using FC.BCVP.NET8.Repository;
using FC.BCVP.NET8.Repository.UnitOfWorks;
using FC.BCVP.NET8.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FC.BCVP.NET8.Extension.ServiceExtensions
{
    /// <summary>
    /// Autofac模块注册
    /// </summary>
    public class AutofacModuleRegister : Autofac.Module
    {
        /// <summary>
        /// 重写Load方法==>其实就是找到指定目录下的dll==>再通过反射的方式获取到数据==>再批量注册
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            //根路径
            var basePath = AppContext.BaseDirectory;

            //仓储实现层dll文件路径
            var repositoryDllFile = Path.Combine(basePath, "FC.BCVP.NET8.Repository.dll");

            //服务实现层dll文件路径
            var servicesDllFile = Path.Combine(basePath, "FC.BCVP.NET8.Service.dll");

            //注册Aop类型
            var aopTypes = new List<Type>() { typeof(ServiceAOP) };
            builder.RegisterType<ServiceAOP>();

            //泛型注入==>实现类==>接口层
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();
            //服务层BaseService也要加入拦截代码，否则拦截器不生效
            builder.RegisterGeneric(typeof(BaseService<,>)).As(typeof(IBaseService<,>))
                .EnableInterfaceInterceptors()
                .InterceptedBy(aopTypes.ToArray())
                .InstancePerDependency();

            //加载Repository.Dll 程序集服务，并注册
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository)
                .AsImplementedInterfaces()
                .PropertiesAutowired()
                .InstancePerDependency();

            //加载Service.Dll 程序集服务，并注册
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            builder.RegisterAssemblyTypes(assemblysServices)
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .PropertiesAutowired()
                .EnableInterfaceInterceptors()
                .InterceptedBy(aopTypes.ToArray());

            builder.RegisterType<UnitOfWorkManage>().As<IUnitOfWorkManage>()
               .AsImplementedInterfaces()
               .InstancePerLifetimeScope()
               .PropertiesAutowired();
        }
    }
}
